package com.jevons.muffin.net;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import io.reactivex.disposables.Disposable;

/**
 * 请求管理
 * 用于取消网络请求
 * @author linaisheng
 * Created at 2019/3/19.
 */

public class HttpRequestManager {

    private static final String TAG = HttpRequestManager.class.getSimpleName();

    private static Map<String, Disposable> requestMap;
    private static HttpRequestManager instance;

    private HttpRequestManager() {
        requestMap = new HashMap<>();
    }

    //单例
    public static HttpRequestManager getInstance() {
        if (instance == null) {
            synchronized (HttpRequestManager.class) {
                if (instance == null) {
                    instance = new HttpRequestManager();
                }
            }
        }
        return instance;
    }

    /**
     * 添加请求
     * @param taskId        标识
     * @param disposable    请求任务
     * @return  是否添加成功
     */
    public synchronized boolean putRequest(String taskId, Disposable disposable) {
        if (taskId == null || taskId.trim().length() == 0) {
            return false;
        }
        if (isRequesting(taskId)) {
            return false;
        }
        requestMap.put(taskId, disposable);
        return true;
    }

    /**
     * 取消请求
     * @param taskId    标识
     * @return
     */
    public synchronized  boolean removeRequest(String taskId) {
        if (isRequesting(taskId)) {
            Disposable disposable = requestMap.remove(taskId);
            //判断是否被取消
            if (!disposable.isDisposed()) {
                disposable.dispose();
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 是否在请求中
     * @param taskId    标识
     * @return
     */
    public boolean isRequesting(String taskId) {
        return requestMap.containsKey(taskId);
    }


    /**
     * 通过uuid获取唯一标识
     * @return
     */
    public String getTaskId() {
       String uuid;
       do {
           uuid = UUID.randomUUID().toString();
       } while (requestMap.containsKey(uuid));
       return uuid;
    }

}
